package LeetCode.month01.day14;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class No994 {
    public static void main(String[] args) {
        int[][] grid = new int[][]{{1,2}};
        for (int i = 0; i < grid.length; i++) {
            System.out.println(Arrays.toString(grid[i]));
        }
        System.out.println(orangesRotting(grid));
    }
    public static int orangesRotting(int[][] grid) {
        List<Integer> lan = new ArrayList<>();
        int nr = grid.length;
        int nc= grid[0].length;
        int day = -1;
        for (int r = 0; r < nr; r++) {
            for (int c = 0; c < nc; c++) {
                if(grid[r][c] ==2){
                    lan.add(r*nc+c);
                }
            }
        }
        while(!lan.isEmpty()){
            day++;
            int len = lan.size();
            while(len>0){
                len--;
                int index = lan.remove(0);
                int row = index/nc;
                int col = index%nc;
                if(row-1>=0&&grid[row-1][col]==1){
                    grid[row-1][col]=2;
                    lan.add((row-1)*nc+col);
                }
                if(row+1<nr&&grid[row+1][col]==1){
                    grid[row+1][col]=2;
                    lan.add((row+1)*nc+col);
                }
                if(col-1>=0&&grid[row][col-1]==1){
                    grid[row][col-1]=2;
                    lan.add(row*nc+col-1);
                }
                if(col+1<nc&&grid[row][col+1]==1){
                    grid[row][col+1]=2;
                    lan.add(row*nc+col+1);
                }
            }
        }
        for (int i = 0; i < nr; i++) {
            for (int j = 0; j < nc; j++) {
                if(grid[i][j]==1) return -1;
            }
        }
        if(day==-1) return 0;
        return day;
    }
}
